package com.youhong.teethcare.receiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.MainActivity;
import com.youhong.teethcare.R;
import com.youhong.teethcare.javabeans.BrushingRecord;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.utils.DBHelper;
import com.youhong.teethcare.utils.Util;

import java.lang.ref.WeakReference;
import java.sql.Time;
import java.util.Calendar;
import java.util.Timer;

/**
 * Created by Administrator on 2018/4/24 0024.
 */
public class TimerService extends Service {

    public static int NOTIFICATION_ID = 9888;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static final int COMMAND_SYNC = 0xAA5;
    public static final String EXTRA_COMMAND_ID = "COMMAND_ID";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "onStartCommand: ");
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        registerReceiver(receiver, filter);

        //MainActivity.mDevice.getBattery();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel("22", "dataService", NotificationManager.IMPORTANCE_NONE);
            chan.setLightColor(Color.BLUE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(chan);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "22");
            startForeground(NOTIFICATION_ID, builder.build());


        }
        return super.onStartCommand(intent, flags, startId);
    }

    NotificationManager mNotificationManager;
    MyHandler mHandler;

    Runnable mTimerRunnable = new Runnable() {
        @Override
        public void run() {

            if (Common.userInfo.isClockSwitch1()
                    && isTimerMatched(Common.userInfo.getClockTime1(),
                    Common.userInfo.getClockDayOfWeek1())) {

                sendNotification();

            }
            if (Common.userInfo.isClockSwitch2()
                    && isTimerMatched(Common.userInfo.getClockTime2(),
                    Common.userInfo.getClockDayOfWeek2())) {
                sendNotification();

            }

            if (Common.userInfo.isClockSwitch3()
                    && isTimerMatched(Common.userInfo.getClockTime2(),
                    Common.userInfo.getClockDayOfWeek2())
            ) {
                sendNotification();

            }
            if (Common.userInfo.isClockSwitch4()
                    && isTimerMatched(Common.userInfo.getClockTime2(),
                    Common.userInfo.getClockDayOfWeek2())
            ) {

                sendNotification();

            }

            handler.postDelayed(this, 1000 * 60);

        }
    };

    private boolean isTimerMatched(String time, int daysOfWeek) {
        Calendar c = Calendar.getInstance();

        int hours, minutes;
        hours = Integer.parseInt(time.substring(0, 2));
        minutes = Integer.parseInt(time.substring(3));

        boolean isTimeMatched = false, weekMatched = false;


        if (c.get(Calendar.HOUR_OF_DAY) == hours && c.get(Calendar.MINUTE) == minutes) {

            isTimeMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && (daysOfWeek & 0x1) != 0) {

            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY && (daysOfWeek & 0x2) != 0) {
            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY && (daysOfWeek & 0x4) != 0) {
            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY && (daysOfWeek & 0x8) != 0) {
            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY && (daysOfWeek & 0x10) != 0) {
            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY && (daysOfWeek & 0x20) != 0) {
            weekMatched = true;
        }

        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && (daysOfWeek & 0x40) != 0) {
            weekMatched = true;
        }

        return weekMatched && isTimeMatched;
    }

    DBHelper dbHelper = null;
    private static final String TAG = "TimerService";
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        
        dbHelper = DBHelper.getDbHelper(getApplicationContext());
        handler = new Handler();

        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);
        handler.post(mTimerRunnable);

    }

    
    private void sendNotification() {

        return;

     /*   mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        String content = null;
        Calendar c = Calendar.getInstance();

        //Good Morning 的时间范围1:00-11:00
        if (c.get(Calendar.HOUR_OF_DAY) >= 1 && c.get(Calendar.HOUR_OF_DAY) < 11) {

            content = getResources().getString(R.string.strings104) +
                    Common.userInfo.getNickName() +
                    getResources().getString(R.string.strings106);
            //   Good Day 的时间范围 11:00-13:00
        } else if (c.get(Calendar.HOUR_OF_DAY) >= 11 && c.get(Calendar.HOUR_OF_DAY) < 13) {

            content = getResources().getString(R.string.strings110) +
                    Common.userInfo.getNickName() +
                    getResources().getString(R.string.strings106);

            //   Good Afternoon的时间范围13:00-18:00
        } else if (c.get(Calendar.HOUR_OF_DAY) >= 13 && c.get(Calendar.HOUR_OF_DAY) < 18) {

            content = getResources().getString(R.string.strings111) +
                    Common.userInfo.getNickName() +
                    getResources().getString(R.string.strings106);
        } else {
            //  Good Evening的时间范围18:00-1:00

            content = getResources().getString(R.string.strings105) + " " +
                    Common.userInfo.getNickName() + " " +
                    getResources().getString(R.string.strings106);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager =
                    (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

            Notification.Builder notification = new Notification
                    .Builder(getApplicationContext())
                    .setContentTitle("您有一条新消息")
                    .setContentText(content)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.icon_app)
                    .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.icon_app))
                    //  .setContentIntent(new Intent())
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setChannelId(getApplicationContext().getPackageName())
                    .setSound(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);

            NotificationChannel channel = new NotificationChannel(
                    getApplicationContext().getPackageName(),
                    "Teethcare",
                    NotificationManager.IMPORTANCE_DEFAULT

            );

            notificationManager.createNotificationChannel(channel);
            notificationManager.notify(0, notification.build());

            //  XUIUtils.Companion.show(title);
        } else {

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this)
                            .setSmallIcon(R.mipmap.icon_app)
                            .setContentTitle(getResources().getString(R.string.notification_title))
                            .setStyle(new NotificationCompat.BigTextStyle()
                                    .bigText(content))
                            .setContentText(content)
                            .setDefaults(Notification.DEFAULT_SOUND);

            //  mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            NOTIFICATION_ID++;

        }*/
    }

    Handler handler = new Handler();

    private static class MyHandler extends Handler {

        private WeakReference<TimerService> activityWeakReference;

        public MyHandler(TimerService activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {


        }
    }

    /**
     * 将同步数据，获取电量，获取固件版本号，放到Service 里面来做
     **/
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //绑定牙刷进行同步时，1.获取电量 ,2.获取刷牙时长,3.同步历史数据
            byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);
            if (values[0] == (byte) 0x13) {

                Common.battery = values[1] & 0xFF;
                MainActivity.mDevice.getBrushingTime();

            } else if (values[0] == (byte) 0x7) {

                Common.userInfo.setBrushTime(values[1] + values[2] + values[3] + values[4]);
                Common.userInfo.SyncToLocal(getApplicationContext());
                MainActivity.mDevice.getHand();

            } else if (values[0] == (byte) 0x36) {

                int hand = values[1] & 0xFF;
                if (hand == 1) {
                    //左手
                    Common.userInfo.setHand(0x1);
                } else {
                    //右手
                    Common.userInfo.setHand(0x0);
                }

                Common.userInfo.SyncToLocal(TimerService.this.getApplicationContext());
                MainActivity.mDevice.getBrushingData((byte) 0x0);

            } else if (values[0] == (byte) 0x15) {

                //结束标识符
                if (values[1] == (byte) 0xFF) {

                    //刷新最新数据时间戳
                    Common.userInfo.setLastSyncTime(Calendar.getInstance().getTimeInMillis());
                    Common.userInfo.SyncToLocal(getApplicationContext());
                    unregisterReceiver(this);
                    return;
                }
                Calendar data_c = Calendar.getInstance();

                int year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0;
                //0为离线刷牙，1为指导刷牙记录
                int type = 1;
                year = Util.ConvertBCD2Decimal(values[2]) + 2000;
                month = Util.ConvertBCD2Decimal(values[3]) - 1;
                day = Util.ConvertBCD2Decimal(values[4]);

                if (values[5] >= 0x24) {
                    //减去0x48
                    hours = Util.ConvertBCD2Decimal((byte) (values[5] - 48));
                    type = 0;

                } else {
                    hours = Util.ConvertBCD2Decimal(values[5]);
                }
                minutes = Util.ConvertBCD2Decimal(values[6]);
                seconds = Util.ConvertBCD2Decimal(values[7]);

                data_c.set(year, month, day, hours, minutes, seconds);

                //新的历史记录
                if (data_c.getTimeInMillis() > Common.userInfo.getLastSyncTime()) {
                    int totalTime = (values[8] & 0xFF) + ((values[9] << 8) & 0xFF00);

                    //牙刷中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
                    //大于3分钟也不做存储
                    if (type == 1) {
                        if (totalTime < 30 || totalTime > 180) {
                            return;
                        }
                        //离线刷牙时;如果刷满固件所设定的时间:离线刷牙的数据总会多出1~2秒的。
                        if (Common.userInfo.getBrushTime() + 1 == totalTime ||
                                Common.userInfo.getBrushTime() + 2 == totalTime
                        ) {
                            totalTime = Common.userInfo.getBrushTime();
                        }
                        //牙刷中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
                        //大于5分钟也不做存储
                    } else {

                        if (totalTime < 30 || totalTime > 300) {
                            return;
                        }


                    }

                    BrushingRecord record = new BrushingRecord();
                    record.setTotalTime(totalTime);
                    record.setStartTime(data_c);

                    //我这边DBHelper type = 0 是指导刷牙数据,离线刷牙数据是 1
                    record.setType(type);//牙刷历史数据
                    int area_count = 0;
                    if (type == 0) {
                        record.setBrushMode(values[10] & 0xFF);
                        record.setBrushLevel(values[11] & 0xFF);
                        int area1 = 0, area2 = 0, area3 = 0, area4 = 0, area5 = 0, area6 = 0;

                        //下门牙外
                        if (values[20] == 10) {
                            area1 += 1;
                            area_count++;
                        }

                        //下门牙内
                        if (values[21] == 10) {
                            area1 += 4;
                            area_count++;
                        }
                        //上门牙外
                        if (values[22] == 10) {
                            area2 += 1;
                            area_count++;
                        }
                        //上门牙内
                        if (values[23] == 10) {
                            area2 += 4;
                            area_count++;
                        }

                        //左下外
                        if (values[24] == 10) {
                            area3 += 1;
                            area_count++;
                        }

                        //左下中
                        if (values[25] == 10) {
                            area3 += 2;
                            area_count++;
                        }

                        //左下内
                        if (values[26] == 10) {
                            area3 += 4;
                            area_count++;
                        }


                        //左上外
                        if (values[27] == 10) {
                            area4 += 1;
                            area_count++;
                        }

                        //左上中
                        if (values[28] == 10) {
                            area4 += 2;
                            area_count++;
                        }

                        //左上内
                        if (values[29] == 10) {
                            area4 += 4;
                            area_count++;
                        }

                        //右下外
                        if (values[30] == 10) {
                            area5 += 1;
                            area_count++;
                        }

                        //右下中
                        if (values[31] == 10) {
                            area5 += 2;
                            area_count++;
                        }

                        //右下内
                        if (values[32] == 10) {
                            area5 += 4;
                            area_count++;
                        }


                        //右上外
                        if (values[33] == 10) {
                            area6 += 1;
                            area_count++;
                        }

                        //右上中
                        if (values[34] == 10) {
                            area6 += 2;
                            area_count++;
                        }

                        //右上内
                        if (values[35] == 10) {
                            area6 += 4;
                            area_count++;
                        }

                        record.setArea1(area1);
                        record.setArea2(area2);
                        record.setArea3(area3);
                        record.setArea4(area4);
                        record.setArea5(area5);
                        record.setArea6(area6);
                    }
                    int percent;
                    if (type == 1) {
                        percent = (int) ((float) totalTime / (float) Common.userInfo.getBrushTime() * 100);
                    } else {

                        percent = (int) ((float) area_count / (float) 16 * 100f);

                    }
                    //如果超出离线刷牙时长的设置，还是100%
                    percent = percent > 100 ? 100 : percent;

                    record.setPercent(percent);
                    record.setSurfaceCount(area_count);
                    dbHelper.insertBrushRecord(record);

                    //累加刷牙积分
                    float ratio = (float) totalTime / (float) Common.userInfo.getBrushTime();

                    if (ratio > 1f) {
                        ratio = 1f;
                    }

                    //离线刷牙数据统一加10分
                    Common.userInfo.setScore((int) 10 + Common.userInfo.getScore());
                    Common.userInfo.SyncToLocal(getApplicationContext());
                }
            }
        }
    };
}
